package com.onenine.app.view;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Looper;
import android.os.MessageQueue;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.onenine.app.R;
import com.onenine.chat.emoji.Constants;
import com.onenine.chat.emoji.EmojiBean;
import com.onenine.chat.emoji.EmojiView;
import com.onenine.chat.emoji.EmoticonsKeyboardUtils;
import com.onenine.chat.emoji.data.EmoticonEntity;
import com.onenine.chat.emoji.listener.EmoticonClickListener;
import com.onenine.chat.emoji.widget.EmoticonsEditText;
import com.onenine.chat.listener.OnClickEditTextListener;
import com.onenine.chat.listener.OnMenuClickListener;
import com.onenine.chat.util.SimpleCommonUtils;
import com.onenine.chat.view.AudioRecordButton;
import com.onenine.chat.view.ChatOperationView;

import java.io.File;
import java.lang.reflect.Field;

/**
 * 评论回复
 */
public class CommentInputView extends LinearLayout
        implements View.OnClickListener, TextWatcher, ViewTreeObserver.OnPreDrawListener {

    private static final String TAG = "CommentInputView";
    private EmoticonsEditText mChatInput;
    private CharSequence mInput;

    private ImageButton mVoiceBtn;
    private ImageButton mEmojiBtn;

    private LinearLayout mMenuItemContainer;

    private AudioRecordButton mRecordVoiceBtn;
    private View btnSend;

    private OnMenuClickListener mListener;
    private OnClickEditTextListener mEditTextListener;
    private EmojiView mEmojiRl;

    private int mHeight;
    public static int sMenuHeight;
    public static int sKeyboardHeight;

    private boolean mPendingShowMenu;

    private MediaPlayer mMediaPlayer = new MediaPlayer();

    private Context mContext;
    private Rect mRect = new Rect();

    public CommentInputView(Context context) {
        super(context);
        init(context);
    }

    public CommentInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CommentInputView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context) {
        mContext = context;
        inflate(context, R.layout.layout_comment_chatinput, this);

        sMenuHeight = context.getResources()
                .getDimensionPixelOffset(R.dimen.emoji_bar_height);
        sKeyboardHeight = sMenuHeight;

        mChatInput = findViewById(R.id.aurora_et_chat_input);
        mVoiceBtn = findViewById(R.id.aurora_menuitem_ib_voice);
        mEmojiBtn = findViewById(R.id.aurora_menuitem_ib_emoji);
        btnSend = findViewById(R.id.btn_send);
        btnSend.setEnabled(false);

        btnSend.setOnClickListener(onMenuItemClickListener);
        mVoiceBtn.setOnClickListener(onMenuItemClickListener);
        mEmojiBtn.setOnClickListener(onMenuItemClickListener);
        btnSend.setOnClickListener(onMenuItemClickListener);

        mMenuItemContainer = findViewById(R.id.aurora_ll_menuitem_container);

        mRecordVoiceBtn = findViewById(R.id.rvb_voice_press);

        mEmojiRl = findViewById(R.id.aurora_rl_emoji_container);

        mChatInput.addTextChangedListener(this);
        mChatInput.setOnBackKeyClickListener(new EmoticonsEditText.OnBackKeyClickListener() {
            @Override
            public void onBackKeyClick() {
                if (mEmojiRl.getVisibility() == VISIBLE) {
                    dismissMenuLayout();
                } else if (isKeyboardVisible()) {
                    EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInput);
                }
            }
        });

        DisplayMetrics dm = getResources().getDisplayMetrics();
        mHeight = dm.heightPixels;
        getViewTreeObserver().addOnPreDrawListener(this);

        mChatInput.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (mEditTextListener != null) {
                    mEditTextListener.onTouchEditText();
                }
                if (!mChatInput.isFocused()) {
                    mChatInput.setFocusable(true);
                    mChatInput.setFocusableInTouchMode(true);
                }
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    dismissEmojiLayout();
                }
                return false;
            }
        });
    }

    EmoticonClickListener emoticonClickListener = new EmoticonClickListener() {
        @Override
        public void onEmoticonClick(Object o, int actionType, boolean isDelBtn) {

            if (isDelBtn) {
                SimpleCommonUtils.delClick(mChatInput);
            } else {
                if (o == null) {
                    return;
                }
                if (actionType == Constants.EMOTICON_CLICK_BIGIMAGE) {
                } else {
                    String content = null;
                    if (o instanceof EmojiBean) {
                        content = ((EmojiBean) o).emoji;
                    } else if (o instanceof EmoticonEntity) {
                        content = ((EmoticonEntity) o).getContent();
                    }

                    if (TextUtils.isEmpty(content)) {
                        return;
                    }
                    int index = mChatInput.getSelectionStart();
                    Editable editable = mChatInput.getText();
                    editable.insert(index, content);
                }
            }
        }
    };

    private void init(Context context, AttributeSet attrs) {
        init(context);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return false;
            }
        });
        SimpleCommonUtils.initEmoticonsEditText(mChatInput);
        mEmojiRl.setAdapter(SimpleCommonUtils.getCommonAdapter(mContext, emoticonClickListener));
    }

    private void setCursor(Drawable drawable) {
        try {
            Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
            f.setAccessible(true);
            f.set(mChatInput, drawable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setMenuClickListener(OnMenuClickListener listener) {
        mListener = listener;
    }

    public void setRecordVoiceListener(AudioRecordButton.AudioFinishRecorderListener listener) {
        this.mRecordVoiceBtn.setAudioFinishRecorderListener(listener);
    }

    public void setOnClickEditTextListener(OnClickEditTextListener listener) {
        mEditTextListener = listener;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mInput = s;
        if (s.length() >= 1 && start == 0 && before == 0) { // Starting input
            btnSend.setEnabled(true);
        } else if (s.length() == 0 && before >= 1) { // Clear content
            btnSend.setEnabled(false);
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    public EditText getInputView() {
        return mChatInput;
    }

    public AudioRecordButton getRecordVoiceButton() {
        return mRecordVoiceBtn;
    }

    private ChatOperationView.OnItemClickListener onOpersationItemClickListener = new ChatOperationView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (view.getId() == R.id.tv_send_image) {
                if (mListener != null && mListener.onExpandOption(0)) {
                    dismissMenuLayout();
                }
            } else if (view.getId() == R.id.tv_camera_image) {
                if (mListener != null && mListener.onExpandOption(1)) {
                    dismissMenuLayout();
                }
            } else if (view.getId() == R.id.tv_video_chat) {
                if (mListener != null && mListener.onExpandOption(2)) {
                    dismissMenuLayout();
                }
            } else if (view.getId() == R.id.tv_audio_chat) {
                if (mListener != null && mListener.onExpandOption(3)) {
                    dismissMenuLayout();
                }
            }
        }
    };

    private OnClickListener onMenuItemClickListener = new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.btn_send) {
                // Allow send text and photos at the same time.
                if (onSubmit()) {
                    mChatInput.setText("");
                }
            } else {
                mChatInput.clearFocus();
                if (view.getId() == R.id.aurora_menuitem_ib_voice) {
                    if (mListener != null && mListener.onSendVoiceMessage()) {
                        if (mRecordVoiceBtn.getVisibility() != View.VISIBLE) {
                            if (isKeyboardVisible()) {
                                mPendingShowMenu = true;
                                EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInput);
                                showRecordVoiceLayout();
                                Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                                    @Override
                                    public boolean queueIdle() {
                                        dismissMenuLayout();
                                        return false;
                                    }
                                });
                            } else {
                                dismissMenuLayout();
                                showRecordVoiceLayout();
                            }
                        } else {
                            dismissRecordVoiceLayout();
                        }
                    }
                } else if (view.getId() == R.id.aurora_menuitem_ib_emoji) {
                    if (mListener != null && mListener.switchToEmojiMode()) {
                        if (mEmojiRl.getVisibility() == VISIBLE) {
                            dismissEmojiLayout();
                            dismissMenuLayout();
                        } else if (isKeyboardVisible()) {
                            mPendingShowMenu = true;
                            EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInput);
                            showEmojiLayout();
                        } else {
                            showMenuLayout();
                            showEmojiLayout();
                        }
                    }
                } else if (view.getId() == R.id.btn_send) {
                    if (mListener != null && mListener.switchToExpandMode()) {
                        if (mEmojiRl.getVisibility() == VISIBLE) {
                            dismissMenuLayout();
                        } else if (isKeyboardVisible()) {
                            mPendingShowMenu = true;
                            EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInput);
                            mEmojiRl.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    showExpandLayout();
                                }
                            }, 100);
                        } else {
                            showMenuLayout();
                            showExpandLayout();
                        }
                    }
                }
            }
        }
    };

    @Override
    public void onClick(View view) {
    }

    public int dp2px(float value) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (value * scale + 0.5f);
    }

    public void dismissMenuLayout() {
        mEmojiRl.setVisibility(GONE);
    }

    public void showMenuLayout() {
        EmoticonsKeyboardUtils.closeSoftKeyboard(mChatInput);
        mEmojiRl.setVisibility(VISIBLE);
    }

    public void showRecordVoiceLayout() {
        mEmojiRl.setVisibility(GONE);
        mRecordVoiceBtn.setVisibility(View.VISIBLE);
        mChatInput.setVisibility(View.GONE);
    }

    public void dismissRecordVoiceLayout() {
        mRecordVoiceBtn.setVisibility(View.GONE);
        mChatInput.setVisibility(View.VISIBLE);
    }

    public void showEmojiLayout() {
        mRecordVoiceBtn.setVisibility(View.GONE);
        mChatInput.setVisibility(View.VISIBLE);
        mEmojiRl.setVisibility(VISIBLE);
        mEmojiBtn.setImageResource(R.drawable.ic_keyboard);
        setMenuContainerHeight(sKeyboardHeight);
    }

    public void showExpandLayout() {
        mRecordVoiceBtn.setVisibility(View.GONE);
        mChatInput.setVisibility(View.VISIBLE);
        mEmojiRl.setVisibility(GONE);
        setMenuContainerHeight(sMenuHeight);
    }

    public void dismissEmojiLayout() {
        mEmojiRl.setVisibility(GONE);
        mEmojiBtn.setImageResource(R.drawable.ic_post_emoji);
    }

    public void setMenuContainerHeight(int height) {
        ViewGroup.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, height);
        mEmojiRl.setLayoutParams(params);
    }

    private boolean onSubmit() {
        return mListener != null && mListener.onSendTextMessage(mInput);
    }

    /**
     * Set camera capture file path and file name. If user didn't invoke this method, will saveOrUpdateGreetFriendApply in
     * default path.
     *
     * @param path     Photo to be saved in.
     * @param fileName File name.
     */
    @Deprecated
    public void setCameraCaptureFile(String path, String fileName) {
        File destDir = new File(path);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mMediaPlayer.release();
        getViewTreeObserver().removeOnPreDrawListener(this);
        mMediaPlayer = null;
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus && mHeight <= 0) {
            this.getRootView().getGlobalVisibleRect(mRect);
            mHeight = mRect.bottom;
            Log.d(TAG, "Window focus changed, height: " + mHeight);
        }
    }

    public boolean isKeyboardVisible() {
        return (getDistanceFromInputToBottom() > 300 && mEmojiRl.getVisibility() == GONE)
                || (getDistanceFromInputToBottom() > (mEmojiRl.getHeight() + 300)
                && mEmojiRl.getVisibility() == VISIBLE);
    }

    public boolean isMenuboardVisible() {
        return mEmojiRl.getVisibility() == VISIBLE;
    }

    @Override
    public boolean onPreDraw() {
        if (mPendingShowMenu) {
            if (isKeyboardVisible()) {
                ViewGroup.LayoutParams params = mEmojiRl.getLayoutParams();
                int distance = getDistanceFromInputToBottom();
                if (distance < mHeight / 2 && distance > 300 && distance != params.height) {
//                    sKeyboardHeight = distance;
//                    params.height = distance;
//                    mEmojiRl.setLayoutParams(params);
                }
                return false;
            } else {
                showMenuLayout();
                mPendingShowMenu = false;
                return false;
            }
        } else {
            if (mEmojiRl.getVisibility() == VISIBLE && isKeyboardVisible()) {
                dismissMenuLayout();
                return false;
            }
        }
        return true;
    }

    public int getDistanceFromInputToBottom() {
        mMenuItemContainer.getGlobalVisibleRect(mRect);
        return mHeight - mRect.bottom;
    }

    private final Runnable measureAndLayout = new Runnable() {
        @Override
        public void run() {
            measure(
                    MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                    MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
            layout(getLeft(), getTop(), getRight(), getBottom());
        }
    };

    @Override
    public void requestLayout() {
        super.requestLayout();
        post(measureAndLayout);
    }

    public void setEditBackgroundResource(int resId) {
        mChatInput.setBackgroundResource(resId);
    }

    public void setEditTextColor(int color) {
        mChatInput.setTextColor(color);
    }

    public void setEditTextHint(String hint) {
        mChatInput.setHint(hint);
    }

    public void clearEditText() {
        mChatInput.setText("");
    }

    public void setTopBottomHorizontalDividerVisible(boolean visible) {
        findViewById(R.id.vl_horizontal1).setVisibility(visible ? View.VISIBLE : View.GONE);
        findViewById(R.id.vl_horizontal2).setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    public void setAudioFormat(boolean isChat) {
        mRecordVoiceBtn.setAudioFormat(isChat);
    }

    public void setEmojiBarBackgroundColor(int color) {
        mEmojiRl.setBackgroundColor(color);
    }

    public boolean isEmojiVisible() {
        return mEmojiRl.getVisibility() == View.VISIBLE;
    }
}


